<template>
  <div class="edit">
    <h3>用户登录</h3>
    <el-form
      :model="ruleForm"
      label-width="120"
      :rules="loginRules"
      ref="ruleForm"
    >
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="ruleForm.userName"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="ruleForm.password"
          type="password"
          show-password
        ></el-input>
      </el-form-item>
      <el-form-item align="center">
        <el-button type="primary" @click="login" round>登录</el-button>
        <el-button @click="resetLogin" type="primary" round>重置</el-button>
      </el-form-item>
    </el-form>
    <el-dropdown trigger="click" size="medium" split-button type="primary">
      登陆选择
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item
          :icon="'el-icon-' + item.icon"
          v-model="item.role"
          v-for="item in roleData"
          :key="item.role"
          @click="checkout(item.role)"
          >{{ item.role }}</el-dropdown-item
        >
      </el-dropdown-menu>
    </el-dropdown>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleData: [
        { role: "admin", icon: "user-solid" },
        { role: "customer", icon: "s-custom" },
        { role: "producer", icon: "user" }
      ],
      role: "admin",
      ruleForm: {
        userName: "admin",
        password: "123456"
      },
      loginRules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
          { min: 6, max: 18, message: "长度在 6 ~ 18 个字符", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    login() {
      const userInfor = {
        userName: this.ruleForm.userName,
        password: this.ruleForm.password
      };
      this.$http.login
        .userLogin(userInfor)
        .then(res => {
          console.log(res);
          if (res !== null) {
            sessionStorage.setItem("userName", userInfor.userName); // 保存用户到本地会话
            this.$message("登陆成功"); //登陆成功
            this.$router.push("/").catch(r => {
              console.log(r);
            });
          } else {
            this.$message("用户名或密码错误");
            //登陆失败
          }
        })
        .catch(error => {
          console.log(error);
          //网络连接失败
        });
    },
    resetLogin() {
      this.$refs.ruleForm.resetFields();
    },
    checkout(infor) {
      this.role = infor.role;
      console.log(infor.role);
    }
  }
};
</script>
<style lang="scss" scoped>
.edit {
  margin: 100px auto;
  width: 500px;
  height: 400px;
  box-shadow: 0 0 20px rgb(3, 116, 3);
  background: #b5da65;
  position: relative;
  .commit {
    position: absolute;
    bottom: 50px;
    left: 130px;
    width: 120px;
  }
}
</style>
